package com.zwr.normal.sharemodel.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeAccessor {
    static Unsafe unsafe;

    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    static Unsafe getUnsafe(){
        return unsafe;
    }
}

class UnsafeTest{
    public static void main(String[] args) throws Exception {
        Unsafe unsafe = UnsafeAccessor.getUnsafe();
        Field id = Student.class.getDeclaredField("id");
        Field name = Student.class.getDeclaredField("name");
        long idOffset = UnsafeAccessor.unsafe.objectFieldOffset(id);
        long nameOffset = UnsafeAccessor.unsafe.objectFieldOffset(name);
        Student student = new Student();
        boolean b = UnsafeAccessor.unsafe.compareAndSwapInt(student, idOffset, 0, 20);
        boolean c = UnsafeAccessor.unsafe.compareAndSwapObject(student, nameOffset, null, "张三");
        System.out.println(student);

    }
}
class Student{
    public volatile int id;
    public volatile String name;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
